package com.yichi;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yichi.adapter.TakeBatteryAdapter;
import com.yichi.device_bean.BatteryStore;
import com.yichi.device_bean.PlcInfo;
import com.yichi.manager.OnHttpResponseListener;
import com.yichi.model.TakeBatteryModel;
import com.yichi.service.DeviceService;
import com.yichi.service.IccardService;
import com.yichi.service.PlatformService;
import com.yichi.service.PlcService;
import com.yichi.util.BeanUtil;
import com.yichi.util.JsonUtil;
import com.yichi.util.MapUtil;
import com.yichi.util.ProgressBar;
import com.yichi.util.StringUtil;
import com.yichi.util.ToastUtil;

import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Response;

public class AdminOperateFragment extends Fragment {
    private final static String TAG = "AdminOperateFragment";
    private static final org.apache.commons.logging.Log log = LogFactory.getLog(AdminOperateFragment.class);

    private RecyclerView recyclerView;
    private TextView tip, continueButton, stopButton, cancel, needTakeText, takeNumber;
    private TextView work_order_number, work_order_title, work_order_content, order_start_time, order_end_time;
    private boolean isTake = true;
    private TakeBatteryAdapter adapter;
    private Map<String, Object> orderMap;
    private Integer opsType;//1取 2存
    private Integer opsNum;//处理数量
    private String orderNum;//工单号
    private Integer orderId;//工单id

    public AdminOperateFragment(Map<String, Object> orderMap) {
        this.orderMap = orderMap;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_admin_operate, container, false);
        findView(view);
        setView();
        initRecyclerView();
        this.renderOrderInfo(this.orderMap);
//        handleCunTest();
        return view;
    }

    /**
     * 渲染工单
     * {
     * "id": 6,
     * "warningId": 1,
     * "opsUserId": 1,
     * "opsUserName": "疯狂的狮子Li",   // 处理人名称
     * "currentCabinetId": 5,          // 机柜id
     * "currentCabinetNum": "nzh001",
     * "currentStationId": 4,
     * "opsBatteryNum": 10,     // 需要处理的电池数量
     * "tackleBatteryNum": 0,  //  解决的电池数量
     * "opsType": 1,           //  处理类型   1 是取   2 是存
     * "opsState": 0,          //  处理状态 ( 字典 )
     * "deadlineTime": "2025-03-14 16:30:13",  // 截止时间
     * "orderNum": "12121231312",
     * "remark": null
     * }
     */
    private void renderOrderInfo(Map<String, Object> map) {
        if(map == null) return;

        opsType = MapUtil.getInteger(map, "opsType");
        opsNum = MapUtil.getInteger(map, "opsBatteryNum") - MapUtil.getInteger(map, "tackleBatteryNum");
        orderNum = MapUtil.getString(map, "orderNum");
        orderId = MapUtil.getInteger(map, "id");

        work_order_number.setText(String.format("工单编号：%s", orderNum));
        work_order_title.setText(String.format("管理员【%s】正在处理", MapUtil.getString(map, "opsUserName")));
        work_order_content.setText(String.format("%s%s块电池", opsType.equals(1) ? "取出" : "存入", opsNum));

        // 获取当前时间
        order_start_time.setText(MapUtil.getString(map, "createTime"));
        order_end_time.setText(MapUtil.getString(map, "deadlineTime"));
        tip.setText(opsType.equals(1) ? "取电" : "存电");
        String opsText = opsType.equals(1) ? "取" : "存";
        needTakeText.setText(String.format("应%s %s 块电池，已%s", opsText, opsNum, opsText));
        takeNumber.setText(String.format("%s", adapter.getTakeBatteryModels().size()));

        continueButton.setText(opsType.equals(1) ? "取出电池" : "存放电池");
        stopButton.setText(opsType.equals(1) ? "结束取电" : "结束存电");
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        RecyclerView.ItemDecoration gridItemDecoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int layoutPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
                if (layoutPosition != 0 && layoutPosition != 1) {
                    outRect.top = 24;
                }
            }
        };
        recyclerView.addItemDecoration(gridItemDecoration);
        adapter = new TakeBatteryAdapter();
        recyclerView.setAdapter(adapter);
    }

    //加载存电数据
    private void addDataItem(TakeBatteryModel model) {
        adapter.addItem(model);
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
    }

    private void setView() {
//        takeData = new ArrayList<TakeBatteryModel>();
//        takeData.add(new TakeBatteryModel(false, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(false, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(true, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(false, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(false, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(true, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(false, true, "DC123912319"));
//        takeData.add(new TakeBatteryModel(false, true, "DC123912319"));
//
//        saveData = new ArrayList<TakeBatteryModel>();
//        saveData.add(new TakeBatteryModel(false, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(false, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(true, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(false, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(false, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(true, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(false, false, "DC123912319"));
//        saveData.add(new TakeBatteryModel(false, false, "DC123912319"));
//
//        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
//
//        RecyclerView.ItemDecoration gridItemDecoration = new RecyclerView.ItemDecoration() {
//            @Override
//            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//                int layoutPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
//                if (layoutPosition != 0 && layoutPosition != 1) {
//                    outRect.top = 24;
//                }
//            }
//        };
//
//        recyclerView.addItemDecoration(gridItemDecoration);
//        adapter = new TakeBatteryAdapter(takeData);
//        recyclerView.setAdapter(adapter);

        //取消
        cancel.setOnClickListener(view -> {
            requireActivity().runOnUiThread(() -> {
                MainActivity mainActivity = (MainActivity) requireActivity();
                mainActivity.goHome();
            });
//            if (isTake) {
//                tip.setText("存电");
//                continueButton.setText("继续放入");
//                stopButton.setText("结束放入");
//                needTakeText.setText("应存 8 块电池，已存");
//                takeNumber.setTextColor(YiChiApplication.application.getResources().getColor(R.color.save_battery_number_color));
//                adapter.setTakeBatteryModels(saveData);
//                adapter.notifyDataSetChanged();
//            } else {
//                tip.setText("取电");
//                continueButton.setText("继续取出");
//                stopButton.setText("结束取出");
//                needTakeText.setText("应取 8 块电池，已取");
//                takeNumber.setTextColor(YiChiApplication.application.getResources().getColor(R.color.take_battery_number_color));
//                adapter.setTakeBatteryModels(takeData);
//                adapter.notifyDataSetChanged();
//            }
//            isTake = !isTake;
        });
        //继续
        continueButton.setOnClickListener(view -> {
            if (opsType == 1) {
                Executors.newSingleThreadExecutor().execute(this::handleQv);
            } else if (opsType == 2) {
                Executors.newSingleThreadExecutor().execute(this::handleCun);
            }
        });
        //结束
        stopButton.setOnClickListener(view -> {
            handleSubmitOpsOrder();
//            testHandleSubmitOpsOrder();
        });
    }

    private void handleCunTest() {
        new Thread(() -> {
            while (true) {
                TakeBatteryModel itemModel = new TakeBatteryModel(false, false, "DC123912319");
                requireActivity().runOnUiThread(() -> {
                    addDataItem(itemModel);
                });

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        }).start();
    }

    //执行存
    private void handleCun() {
        //1 是否有空位
        BatteryStore inputStore = DeviceService.inst.getRandomInputStore();
        if (inputStore == null) {
            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(requireActivity(), "暂时没有空仓位");
            });
            return;
        }
        Log.i(TAG, "找到空位：" + inputStore.getStoreNo());

        //初始ui
        requireActivity().runOnUiThread(() -> {
            cancel.setVisibility(View.GONE);
            continueButton.setVisibility(View.GONE);
            stopButton.setVisibility(View.GONE);
            TakeBatteryModel itemModel = new TakeBatteryModel(true, false, "存电中...");
            addDataItem(itemModel);
        });
        Log.i(TAG, "UI发生跳转1");

        //2 随机开一个门
        PlcService.inst.handleOpenDoor(inputStore.getStoreNo());
        Log.i(TAG, String.format("发送打开%s号仓门命令", inputStore.getStoreNo()));

        //3 门是否打开
        boolean openDoor = PlcService.inst.isOpenDoor(inputStore.getStoreNo());
        if (!openDoor) {
            requireActivity().runOnUiThread(() -> {
                int pos = adapter.getTakeBatteryModels().size() - 1;
                adapter.removeItem(pos);
                ToastUtil.show(requireActivity(), "仓门未打开成功");
            });
            return;
        }
        inputStore.setDoorOpen(true);
        DeviceService.inst.saveData();
        Log.i(TAG, "仓门已打开");

        //4 是否关门
        PlcInfo plcInfo = PlcService.inst.isCloseDoor(inputStore.getStoreNo());
        if (plcInfo == null) {
            requireActivity().runOnUiThread(() -> {
                int pos = adapter.getTakeBatteryModels().size() - 1;
                adapter.removeItem(pos);
                ToastUtil.show(requireActivity(), "操作中断");
            });
            return;
        }
        inputStore.setDoorOpen(false);
        DeviceService.inst.saveData();
        Log.i(TAG, "仓门已关闭");

        //5 是否放入电池
        String[] batteryNoArr = IccardService.inst.queryBatteryNo();
        if (batteryNoArr == null || batteryNoArr.length < 3) {
            requireActivity().runOnUiThread(() -> {
                int pos = adapter.getTakeBatteryModels().size() - 1;
                adapter.removeItem(pos);
                ToastUtil.show(requireActivity(), "未放入电池");
            });
            return;
        }
        String batteryNo = batteryNoArr[inputStore.getStoreNo() - 1];
        if (StringUtil.isEmpty(batteryNo)) {
            requireActivity().runOnUiThread(() -> {
                int pos = adapter.getTakeBatteryModels().size() - 1;
                adapter.removeItem(pos);
                ToastUtil.show(requireActivity(), "未放入电池");

                //读不出电池，逻辑有问题》》》》》》》》？？？？？？？？？？？？？？？？？
                int opsSize = adapter.getTakeBatteryModels().size();
                //取消按钮
                if (opsSize > 0) {
                    cancel.setVisibility(View.GONE);
                } else {
                    cancel.setVisibility(View.VISIBLE);
                }
                //继续按钮
                if (opsSize >= opsNum) {
                    continueButton.setVisibility(View.GONE);
                } else {
                    continueButton.setVisibility(View.VISIBLE);
                    continueButton.setText("继续存电");
                }
                //结束按钮
                stopButton.setVisibility(View.VISIBLE);
            });
            return;
        }
        Log.i(TAG, "存入电池编号：" + batteryNo);

        //6 更新数据
        inputStore.setHasBattery(true);
        inputStore.setBatteryNo(batteryNo);
        inputStore.setLockStatus(0);
        DeviceService.inst.saveData();
        Log.i(TAG, "更新完数据");

        //7 更新ui
        requireActivity().runOnUiThread(() -> {
            int opsSize = adapter.getTakeBatteryModels().size();
            //显示电池编号
            int pos = opsSize - 1;
            adapter.updateItem(pos, batteryNo);
            //更新下已操作数量
            takeNumber.setText(String.format("%s", opsSize));
            //取消按钮
            cancel.setVisibility(View.GONE);
            //继续按钮
            if (opsSize >= opsNum) {
                continueButton.setVisibility(View.GONE);
            } else {
                continueButton.setVisibility(View.VISIBLE);
                continueButton.setText("继续存电");
            }
            //结束按钮
            stopButton.setVisibility(View.VISIBLE);
        });
    }

    //执行取
    private void handleQv() {
        //1 取电仓是否有电池
        BatteryStore outputStore = DeviceService.inst.getRandomOutputStoreHas();
        if (outputStore == null) {
            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(requireActivity(), "取出仓暂无电池");
            });
            return;
        }

        //初始ui
        requireActivity().runOnUiThread(() -> {
            cancel.setVisibility(View.GONE);
            continueButton.setVisibility(View.GONE);
            stopButton.setVisibility(View.GONE);
            TakeBatteryModel itemModel = new TakeBatteryModel(true, false, "取电中...");
            addDataItem(itemModel);
        });

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //2 开门
        PlcService.inst.handleOpenDoor(outputStore.getStoreNo());
        Log.i(TAG, "发送开门指令");

        //3 门是否打开
        boolean openDoor = PlcService.inst.isOpenDoor(outputStore.getStoreNo());
        if (!openDoor) {
            requireActivity().runOnUiThread(() -> {
                int pos = adapter.getTakeBatteryModels().size() - 1;
                adapter.removeItem(pos);
                ToastUtil.show(requireActivity(), "仓门未打开");
                //回首页
            });
            return;
        }
        outputStore.setDoorOpen(true);
        DeviceService.inst.saveData();
        Log.i(TAG, "门已打开");

        //4 是否关门
        PlcInfo plcInfo = PlcService.inst.isCloseDoor(outputStore.getStoreNo());
        if (plcInfo == null) {
            requireActivity().runOnUiThread(() -> {
                int pos = adapter.getTakeBatteryModels().size() - 1;
                adapter.removeItem(pos);
                ToastUtil.show(requireActivity(), "操作中断");
            });
            return;
        }
        outputStore.setDoorOpen(false);
        DeviceService.inst.saveData();
        Log.i(TAG, "门已关闭");

        //5 是否取走电池
        Integer batteryStatusByStoreNo = plcInfo.getBatteryStatusByStoreNo(outputStore.getStoreNo());
        if (batteryStatusByStoreNo.equals(1)) {
            int pos = adapter.getTakeBatteryModels().size() - 1;
            adapter.removeItem(pos);
            ToastUtil.show(requireActivity(), "没取走电池");
            return;
        }
        Log.i(TAG, "已取走电池");
        String batteryNo = outputStore.getBatteryNo();

        //6 更新下数据
        BeanUtil.setBatteryStoreEmpty(outputStore);
        DeviceService.inst.saveData();

        //7 更新ui
        requireActivity().runOnUiThread(() -> {
            int opsSize = adapter.getTakeBatteryModels().size();
            //1 更新下列表
            int pos = adapter.getTakeBatteryModels().size() - 1;
            Log.i(TAG, "电池编号:" + batteryNo);
            adapter.updateItem(pos, batteryNo);
            //2 更新下已操作数量
            takeNumber.setText(String.format("%s", opsSize));
            //3 按钮
            //取消按钮
            cancel.setVisibility(View.GONE);
            //继续按钮
            if (opsSize >= opsNum) {
                continueButton.setVisibility(View.GONE);
            } else {
                continueButton.setVisibility(View.VISIBLE);
                continueButton.setText("继续取电");
            }
            //结束按钮
            stopButton.setVisibility(View.VISIBLE);
        });

        Log.i(TAG, "取电完成");
    }

    //测试提交工单
    private void testHandleSubmitOpsOrder() {
        List<String> batteryNoList = new ArrayList<>();
        batteryNoList.add("DC0001");
        batteryNoList.add("DC0002");
        try {
            PlatformService.tackleBatteryAsync(orderId, batteryNoList, new OnHttpResponseListener() {
                @Override
                public void success(Call call, Response response) throws IOException {
                    String s = response.body().string();
                    Map<String, Object> map = JsonUtil.parseMap(s);
                    Integer code = MapUtil.getInteger(map, "code");
                    String msg = MapUtil.getString(map, "msg");
                    if (code != 200) {
                        requireActivity().runOnUiThread(() -> {
                            ToastUtil.show(requireActivity(), "提交失败：" + msg);
                        });
                        return;
                    }
                    //重置全局数据
                    DeviceService.inst.setDeviceOperInfo(null);
                    //返回首页
                    requireActivity().runOnUiThread(() -> {
                        MainActivity mainActivity = (MainActivity) requireActivity();
                        mainActivity.goHome();
                    });
                }

                @Override
                public void failed(Call call, IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                    requireActivity().runOnUiThread(() -> {
                        ToastUtil.show(requireActivity(), "提交失败：" + e.getMessage());
                    });
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(requireActivity(), "提交失败：" + e.getMessage());
            });
        }
    }

    //提交维护工单
    private void handleSubmitOpsOrder() {
        //1 是否存取过
        int size = adapter.getTakeBatteryModels().size();
        if (size <= 0) {
            ToastUtil.show(requireActivity(), "不能提交");
            return;
        }

        //2 获取数据
        List<TakeBatteryModel> modelList = adapter.getTakeBatteryModels();
        List<String> batteryNoList = modelList.stream().map(TakeBatteryModel::getBatteryNumber).collect(Collectors.toList());

        //3 提交平台
        ProgressBar progressBar = new ProgressBar(getContext(), R.style.CommProgressDialog);
        progressBar.show();
        try {
            PlatformService.tackleBatteryAsync(orderId, batteryNoList, new OnHttpResponseListener() {
                @Override
                public void success(Call call, Response response) throws IOException {
                    progressBar.dismiss();
                    String s = response.body().string();
                    Map<String, Object> map = JsonUtil.parseMap(s);
                    Integer code = MapUtil.getInteger(map, "code");
                    String msg = MapUtil.getString(map, "msg");
                    if (code != 200) {
                        requireActivity().runOnUiThread(() -> {
                            ToastUtil.show(requireActivity(), "提交失败：" + msg);
                        });
                        return;
                    }
                    //重置全局数据
                    DeviceService.inst.setDeviceOperInfo(null);
                    //返回首页
                    requireActivity().runOnUiThread(() -> {
                        MainActivity mainActivity = (MainActivity) requireActivity();
                        Log.i(TAG, String.format("mainActivity是否null：%s", mainActivity == null));
                        mainActivity.goHome();
                    });
                }

                @Override
                public void failed(Call call, IOException e) {
                    progressBar.dismiss();
                    Log.e(TAG, e.getMessage(), e);
                    requireActivity().runOnUiThread(() -> {
                        ToastUtil.show(requireActivity(), "提交失败：" + e.getMessage());
                    });
                }
            });
        } catch (Exception e) {
            progressBar.dismiss();
            Log.e(TAG, e.getMessage(), e);
            ToastUtil.show(requireActivity(), "提交失败：" + e.getMessage());
        }
    }

    private void findView(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        tip = view.findViewById(R.id.tip);
        continueButton = view.findViewById(R.id.continue_button);
        stopButton = view.findViewById(R.id.stop_button);
        cancel = view.findViewById(R.id.cancel);
        needTakeText = view.findViewById(R.id.need_take_text);
        takeNumber = view.findViewById(R.id.take_number);

        work_order_number = view.findViewById(R.id.work_order_number);
        work_order_title = view.findViewById(R.id.work_order_title);
        work_order_content = view.findViewById(R.id.work_order_content);
        order_start_time = view.findViewById(R.id.order_start_time);
        order_end_time = view.findViewById(R.id.order_end_time);
    }

}
